<?php
ob_start(); // 开始输出缓冲
if (!file_exists(__DIR__ . '/settings.json') || !file_exists(__DIR__ . '/db.php')) {
    header("Location: install.php");
    exit;
}
require 'db.php';
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$settings_file = __DIR__ . '/settings.json';
$settings = file_exists($settings_file) ? json_decode(file_get_contents($settings_file), true) : ['title' => '私人网盘'];
$site_title = $settings['title'];

$user_id = $_SESSION['user_id'];

// 启用错误显示（调试用，上线可移除）
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$stmt = $conn->prepare("SELECT username, role FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_username'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo "<script>alert('CSRF 验证失败！'); history.back();</script>";
        ob_flush();
        exit;
    }
    $new_username = trim($_POST['new_username']);
    if (strlen($new_username) < 3 || strlen($new_username) > 191) {
        echo "<script>alert('用户名长度必须在3到191个字符之间！'); history.back();</script>";
        ob_flush();
        exit;
    }
    $check_stmt = $conn->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
    $check_stmt->bind_param("si", $new_username, $user_id);
    $check_stmt->execute();
    if ($check_stmt->get_result()->num_rows > 0) {
        echo "<script>alert('用户名已存在！'); history.back();</script>";
        ob_flush();
        exit;
    }
    $stmt = $conn->prepare("UPDATE users SET username = ? WHERE id = ?");
    $stmt->bind_param("si", $new_username, $user_id);
    if ($stmt->execute()) {
        header("Location: user_center.php?update=username_success");
        ob_flush();
        exit;
    } else {
        echo "<script>alert('用户名修改失败：" . htmlspecialchars($stmt->error, ENT_QUOTES, 'UTF-8') . "'); history.back();</script>";
        ob_flush();
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_password'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo "<script>alert('CSRF 验证失败！'); history.back();</script>";
        ob_flush();
        exit;
    }
    $new_password = $_POST['new_password'];
    if (strlen($new_password) < 6) {
        echo "<script>alert('密码至少6位！'); history.back();</script>";
        ob_flush();
        exit;
    }
    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
    $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
    $stmt->bind_param("si", $hashed_password, $user_id);
    if ($stmt->execute()) {
        header("Location: user_center.php?update=password_success");
        ob_flush();
        exit;
    } else {
        echo "<script>alert('密码修改失败：" . htmlspecialchars($stmt->error, ENT_QUOTES, 'UTF-8') . "'); history.back();</script>";
        ob_flush();
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_id'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo "<script>alert('CSRF 验证失败！'); history.back();</script>";
        ob_flush();
        exit;
    }
    $delete_id = (int)$_POST['delete_id'];
    $stmt = $conn->prepare("SELECT path FROM files WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ii", $delete_id, $user_id);
    $stmt->execute();
    $file = $stmt->get_result()->fetch_assoc();
    if ($file) {
        if (unlink($file['path'])) {
            $stmt = $conn->prepare("DELETE FROM files WHERE id = ? AND user_id = ?");
            $stmt->bind_param("ii", $delete_id, $user_id);
            if ($stmt->execute()) {
                header("Location: user_center.php?delete=success"); // 使用 header 跳转
                ob_flush();
                exit;
            } else {
                echo "<script>alert('数据库删除失败：" . htmlspecialchars($stmt->error, ENT_QUOTES, 'UTF-8') . "'); history.back();</script>";
                ob_flush();
                exit;
            }
        } else {
            echo "<script>alert('文件删除失败：无法移除文件'); history.back();</script>";
            ob_flush();
            exit;
        }
    } else {
        echo "<script>alert('文件不存在或无权限！'); history.back();</script>";
        ob_flush();
        exit;
    }
}

$stmt = $conn->prepare("SELECT f.id, f.name, f.path, f.upload_time, f.category_id, c.name AS category_name 
                       FROM files f 
                       LEFT JOIN categories c ON f.category_id = c.id 
                       WHERE f.user_id = ? 
                       ORDER BY f.upload_time DESC");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$files = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户中心 - <?= htmlspecialchars($site_title) ?></title>
    <link href="/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="<?= $settings['theme'] === 'dark' ? 'bg-dark text-white' : '' ?>">
    <nav class="navbar navbar-expand-lg <?= $settings['theme'] === 'dark' ? 'navbar-dark bg-dark' : 'navbar-light bg-light' ?>">
        <div class="container">
            <a class="navbar-brand" href="index.php"><?= htmlspecialchars($site_title) ?></a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a class="nav-link" href="index.php">首页</a></li>
                    <li class="nav-item"><a class="nav-link" href="upload.php">上传文件</a></li>
                    <li class="nav-item"><a class="nav-link" href="user_center.php">用户中心</a></li>
                    <?php if ($_SESSION['role'] === 'admin'): ?>
                        <li class="nav-item"><a class="nav-link" href="admin/index.php">后台管理</a></li>
                    <?php endif; ?>
                    <li class="nav-item"><a class="nav-link" href="logout.php">退出</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <main class="container py-5">
        <h2>用户中心</h2>
        
        <?php if (isset($_GET['update']) && $_GET['update'] === 'username_success'): ?>
            <div class="alert alert-success">用户名修改成功！</div>
        <?php elseif (isset($_GET['update']) && $_GET['update'] === 'password_success'): ?>
            <div class="alert alert-success">密码修改成功！</div>
        <?php elseif (isset($_GET['delete']) && $_GET['delete'] === 'success'): ?>
            <div class="alert alert-success">文件删除成功！</div>
        <?php endif; ?>

        <div class="card mb-4">
            <div class="card-header">个人信息</div>
            <div class="card-body">
                <p><strong>用户名：</strong> <?= htmlspecialchars($user['username']) ?></p>
                <p><strong>角色：</strong> <?= htmlspecialchars($user['role'] === 'admin' ? '管理员' : '普通用户') ?></p>
                
                <form method="POST" class="mb-3">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                    <input type="hidden" name="update_username" value="1">
                    <div class="mb-3">
                        <label for="new_username" class="form-label">新用户名（3-191位）</label>
                        <input type="text" class="form-control" id="new_username" name="new_username" value="<?= htmlspecialchars($user['username']) ?>" required>
                    </div>
                    <button type="submit" class="btn btn-primary">修改用户名</button>
                </form>

                <form method="POST">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                    <input type="hidden" name="update_password" value="1">
                    <div class="mb-3">
                        <label for="new_password" class="form-label">新密码（至少6位）</label>
                        <input type="password" class="form-control" id="new_password" name="new_password" required>
                    </div>
                    <button type="submit" class="btn btn-primary">修改密码</button>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header">我的文件</div>
            <div class="card-body">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>文件名</th>
                            <th>大小</th>
                            <th>分类</th>
                            <th>上传时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $index = 1; while ($file = $files->fetch_assoc()): ?>
                            <tr>
                                <td><?= $index++ ?></td>
                                <td><?= htmlspecialchars($file['name']) ?></td>
                                <td><?= round(filesize($file['path']) / 1024, 2) ?> KB</td>
                                <td><?= htmlspecialchars($file['category_name'] ?? '无分类') ?></td>
                                <td><?= $file['upload_time'] ?></td>
                                <td>
                                    <a href="download.php?id=<?= $file['id'] ?>" class="btn btn-primary btn-sm">下载</a>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('确认删除？');">
                                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                                        <input type="hidden" name="delete_id" value="<?= $file['id'] ?>">
                                        <button type="submit" class="btn btn-danger btn-sm">删除</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>

    <footer class="bg-dark text-white text-center py-3">
        <p>© 2025 <?= htmlspecialchars($site_title) ?></p>
    </footer>

    <script src="/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php ob_end_flush(); // 结束并输出缓冲 ?>